package com.suep.system.aspect;

import com.suep.system.annotation.RequireRole;
import com.suep.system.exception.RoleCheckException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 角色权限认证切面
 *
 * @author 罗不丢
 * @since 2025/2/24
 */

@Aspect
@Component
public class RoleAspect {

    @Before("@annotation(requireRole)")
    public void checkRole(JoinPoint joinPoint, RequireRole requireRole) throws Throwable {
        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RoleCheckException("没有找到请求域");
        }
        HttpServletRequest request = attributes.getRequest();

        // 从请求域中获取角色信息，本系统不会允许用户存在多种角色情况
        String userRole = (String)request.getAttribute("role");
        if (userRole == null) {
            throw new RoleCheckException("用户角色信息为空");
        }

        // 获取注解中要求的角色
        String checkRole = requireRole.role();

        // 检查角色
        boolean hasRequiredRole = false;
        if(checkRole.equals(userRole)){
            hasRequiredRole=true;
        }
        if (!hasRequiredRole) {
            throw new RoleCheckException("用户没有权限访问该功能");
        }
    }

    // 辅助方法，用于获取方法上的注解
    private <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> annotationClass) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        return method.getAnnotation(annotationClass);
    }
}
